
import PAM30
import sys
import time

def get_link_by_text(ie, text):
    l = ie.getElementsList("a")
    for e in l:
        if e.innerText==text:
            return e
    else:
        return None

def get_link_by_id(ie, id):
    l = ie.getElementsList("a")
    for e in l:
        if e.id==id:
            return e
    else:
        return None

def get_div_by_text(ie, text):
    #!FIXME! "top"
    l = ie.getElementsList("div")
    for e in l:
        if e.classname=="top":
            if text==e.innerText.strip().rstrip():
                return e
            #print e.innerText
    else:
        return None

def get_li_by_text(ie, text):
    l = ie.getElementsList("li")
    for e in l:
        if text==e.innerText.strip().rstrip():
            return e
    else:
        return None

def get_li_by_id(ie, id):
    l = ie.getElementsList("li")
    for e in l:
        if e.id==id:
            return e
    else:
        return None

def get_image_by_alt(ie, alt):
    l = ie.getElementsList("IMG")
    for e in l:
        if e.alt==alt:
            return e
    else:
        return None

def get_input_element_by_id(ie, id):
    l = ie.getElementsList("INPUT")
    for e in l:
        if e.id==id:
            return e
    else:
        return None


def check_money(ie):
    return  float(ie.getDiv(MONEYVALUE).innerText)

def check_health(ie):
    li_wellnessBar = get_li_by_id(ie, WELLNESS)
    children = ie.getElementChildren(li_wellnessBar)
    return float(children[1].innerText)

def get_work_train_reward(ie, text):
    if ie.divExists(text):
        div = ie.getDiv(text)
        ul = ie.getElementChildren(div)   
        work_link = ul[2]
        train_link = ul[4]
        reward_link = ul[6]
        return work_link, train_link, reward_link
    else:
        return None, None, None

def work(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks")
    
    if w:
        #click work
        ie.clickLink(w)
        ie._wait()
        #0 gold 10% improve
        div = get_div_by_text(ie, "Single Espresso 0")
        if div:
            ie.clickElement(div)
            # Start working
            h = get_link_by_id(ie, "form_submit")
            ie.clickLink(h)
            sys.stdout.write("working... ")
            ie._wait()
            sys.stdout.write("Done\n")
        #fired? find a new job
        else:
            print "\tFired? finding a new job"
            pass #FIXME
            
    else:
        print " Work not available"
    
def train(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks_full")
    if t:
        ie.clickLink(t)
        ie._wait()
        #0 gold 10% improve
        div = get_div_by_text(ie, "Army boots 0")
        ie.clickElement(div)
        # Start trainning
        h = get_link_by_id(ie, "form_submit")
        ie.clickLink(h)
        ie._wait()
        print "Done"
    else:
        print "train not available"

def reward(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks_full")
    if r:
        ie.clickLink(r)
        ie._wait()
        h = get_link_by_text(ie, "Ok")
        ie.clickLink(h)
        ie._wait()
        print "Done"
    else:
        print "Daily reward not available"

def buy_eat_food(ie):
    li_DailyConsumtionTrigger = get_li_by_id(ie, DAILYCONSUMTION)
    children = ie.getElementChildren(li_DailyConsumtionTrigger)
    eat_buy = children[1].innerText
    while ((children[1].innerText.strip().rstrip()=='Eat food') and (check_health(ie)<99)):
        #eat
        ie.clickLink(get_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
        ie._wait()
        print "\tEat one food, now health is %d"%check_health(ie)
    if children[1].innerText.strip().rstrip()=='Buy food':
        sys.stdout.write("\tgoing to buy... ")
        #buy
        ie.clickLink(get_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
        print "Done"
    

TARGET_URL = "http://www.erepublik.com/en" 
WELLNESS = "wellnessBar"
DAILYCONSUMTION= "DailyConsumtion"
DAILYCONSUMTIONTRIGGER = "DailyConsumtionTrigger"
MONEYVALUE = "side_bar_natural_account_value"

url = TARGET_URL
username = "dinnerforfree"
password = "onceupon!"

NAME_ID = u'citizen_name'
PASS_ID = u'citizen_password'
BUTTON_LOGIN = 'commit'

#open url
ie = PAM30.PAMIE()
print "\tIE opened"
ie.navigate(url) 
sys.stdout.write("\topening URL... ")
ie._wait()
sys.stdout.write("\tDone\n")

#login
ie.setTextBox(get_input_element_by_id(ie, NAME_ID),username)
ie.setTextBox(get_input_element_by_id(ie, PASS_ID),password)
ie.clickButton(BUTTON_LOGIN)
sys.stdout.write("\tLogging in with username %s... "%username)
ie._wait()
sys.stdout.write("\tDone\n")

if (check_health(ie) >= 92) or (check_money(ie) < 5):
    print "\thealth is %d, money is %d"%(check_health(ie), check_money(ie))
    sys.stdout.write("\tGoing to work... ")
    work(ie)
    sys.stdout.write("\tGoing to train... ")
    train(ie)
    sys.stdout.write("\tGoing to daily reward... ")
    reward(ie) 
    buy_eat_food(ie)
else:
    buy_eat_food(ie)
    work(ie)
    if (check_health(ie) < 92):
        buy_eat_food(ie)
    train(ie)
    reward(ie)


#try
sys.stdout.write("\tgoing to buy... ")
#buy
ie.clickLink(get_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
ie._wait()
td = get_td_by_classname(ie, "m_stock")
count = float(td.innerText)
td = get_td_by_classname(ie, "m_price stprice")
price = float(td.innerText.split(" ")[0])
money = check_money(ie)
health = check_health(ie)
i = get_element_by_classname(ie, "INPUT", "shadowed buyField")
i.value = int(min(count, money/price, (100-health)/2))
td = get_td_by_classname(ie, "m_buy")
children = ie.getElementChildren(td)
link = children[0]
ie.clickLink(link)
ie._wait()
li_DailyConsumtionTrigger = get_li_by_id(ie, DAILYCONSUMTION)
children = ie.getElementChildren(li_DailyConsumtionTrigger)
eat_buy = children[1].innerText
while (
    (
        ie.getElementChildren(get_li_by_id(ie, DAILYCONSUMTION))[1].innerText.strip().rstrip()=='Eat food'
    )
    and (check_health(ie)<99)
):
    print "%s, %d"%(ie.getElementChildren(get_li_by_id(ie, DAILYCONSUMTION))[1].innerText, check_health(ie))
    ie.clickLink(get_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
    ie._wait()

print "Done"
